package com.sophialex.health.record.common.bind.swt.validators;

import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

public class IntRangeValidator implements IValidator {
	private int min;
	private int max;
	private boolean leftIncluded;
	private boolean rightIncluded;
	private String err;

	public IntRangeValidator(int min, int max, boolean leftIncluded,
			boolean rightIncluded, String err) {
		this.min = min;
		this.max = max;
		this.leftIncluded = leftIncluded;
		this.rightIncluded = rightIncluded;
		this.err = err;
	}

	public IStatus validate(Object value) {
		if (!(value instanceof String) && !(value instanceof Integer))
			throw new RuntimeException("只支持String与int参数");
		int i = Integer.MAX_VALUE;
		try {
			i = Integer.parseInt(value + "");
		} catch (NumberFormatException e) {
			throw new NumberFormatException(value + "不能转化为有效的整数");
		}
		if (min < i && i < max || min == i && leftIncluded || i == max
				&& rightIncluded)
			return Status.OK_STATUS;
		return ValidationStatus.error(err);

	}

}
